package com.logic.lhub.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.logic.lhub.fusion.FusionCode;

import java.io.File;


/**
 * <Pre>
 * DownLoad工具类
 * </Pre>
 *
 * @author Xian
 * @version 1.0
 * Create by 15/5/5 下午9:09
 */
@SuppressWarnings("deprecation")
@TargetApi(11)
public class DownloadUtil {
    private static DownloadManager downloadManager;
    private static SharedPreferences prefs;
    public static final String DOWNLOAD_ID = "download_id_version_";
    private static Context mContext;
    private static int isOpen = 0;

    private static final int COMPLETED = 0;
    private static final int FAILED = 1;
    private static final int START = 2;
    private static final int LOADING = 3;

    public static void DownLoadFile(final Context mContext, String downLoadUrl, final String version) {
        //保存位置
        //关于下边的File.separator原文The system-dependent string used to separate components in filenames
        // ('/').
        //其实就是代表了一个斜杠
        final File filepath = new File(mContext.getExternalFilesDir(null).getPath() + "/download/" + "LHubApp_" + version + ".apk");
        if (!filepath.exists()) {
//            filepath.mkdir();//如果路径不存在就先创建路径
        }

        // 准备进度条Progress弹窗
        final ProgressDialog dialog = new ProgressDialog(mContext);
        dialog.setCancelable(false);// 设置是否可以通过点击Back键取消
        dialog.setTitle("下载中");
        //Progress弹窗设置为水平进度条
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        //httputils网络请求工具
        HttpUtils http = new HttpUtils();

        @SuppressLint("HandlerLeak") final Handler handlerUi = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == START) {
                    dialog.show();//展示关闭弹窗
                } else if (msg.what == COMPLETED) {
                    dialog.dismiss();//关闭弹窗

                    //安装下载的文件（如果不是apk这里可以不用安装，下载完成后自己看着办吧）
//          intent
//              .setDataAndType(FileProvider.getUriForFile(activity, applicationId + ".provider",
//                  new File(filepath.getPath().toString())),
//                  "application/vnd.android.package-archive");
                    try {
//                            downloadManager.openDownloadedFile(id).;
                        File apkfile = new File(mContext.getExternalFilesDir(null).getPath() + "/download/" + "LHubApp_" + version + ".apk");
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        Uri uri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            uri = FileProvider.getUriForFile(mContext, "com.logic.lhub.fileprovider", apkfile);
                        } else {
                            uri = Uri.parse("file://" + apkfile.toString());
                        }
                        i.setDataAndType(uri, "application/vnd.android.package-archive");
                        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        mContext.startActivity(i);
                        android.os.Process.killProcess(android.os.Process.myPid());
//                            isOpen = 1;
                    } catch (Exception e) {
                        e.printStackTrace();
                        dialog.dismiss();
                        Toast.makeText(mContext, "下载出错，请重试！", Toast.LENGTH_LONG).show();
                    }
                } else if (msg.what == FAILED) {
//                    dialog.dismiss();//关闭弹窗
//                    if (msg.getData().getInt("ErrorCode") == 416) {
//                        Intent intent = new Intent(Intent.ACTION_VIEW);
////            intent
////                .setDataAndType(
////                    FileProvider.getUriForFile(activity, applicationId + ".provider",
////                        new File(filepath.getPath().toString())),
////                    "application/vnd.android.package-archive");
//                        try {
////                            downloadManager.openDownloadedFile(id).;
//                            File apkfile = new File(FusionCode.DOWNLOAD_SAVE_APK_PATH + "qigyou_" + version + ".apk");
//                            Intent i = new Intent(Intent.ACTION_VIEW);
//                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
//                                    "application/vnd.android.package-archive");
//                            mContext.startActivity(i);
//                            android.os.Process.killProcess(android.os.Process.myPid());
////                            isOpen = 1;
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }

                    try {
//                            downloadManager.openDownloadedFile(id).;
                        File apkfile = new File(mContext.getExternalFilesDir(null).getPath() + "/download/" + "LHubApp_" + version + ".apk");
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                                "application/vnd.android.package-archive");
                        mContext.startActivity(i);
                        android.os.Process.killProcess(android.os.Process.myPid());
//                            isOpen = 1;
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(mContext, "下载失败，请重试！", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }
                } else if (msg.what == LOADING) {
                    dialog.setMax((int) msg.getData().getLong("total"));
                    dialog.setProgress((int) msg.getData().getLong("current"));
                }
            }
        };

        //下载请求
        /*
             第一参数：downLoadUrl是网络下载位置
             第二参数：filepath.getPath()是下载保存位置
            第三个参数：如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
            第四个参数：如果从请求返回信息中获取到文件名，下载完成后自动重命名。
            第五个参数：下载的监听
         */

        final HttpHandler handler = http
                .download(downLoadUrl, filepath.getPath(), true, false, new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                        Message msg = new Message();
                        msg.what = START;
                        handlerUi.sendMessage(msg);
                        Log.i("开", "onStart: 开始下载");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        Message msg = new Message();
                        msg.what = LOADING;
                        Bundle bundle = new Bundle();

                        bundle.putLong("total", total);
                        bundle.putLong("current", current);

                        msg.setData(bundle);
                        handlerUi.sendMessage(msg);
                        Log.i("下载中", "onLoading:总共： " + total + "已下" + current);

                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {

                        Message msg = new Message();
                        msg.what = COMPLETED;
                        handlerUi.sendMessage(msg);
                        //卸载
                  /*    Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");//package:com
                  .demo.CanavaCancel应用的包名
                        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
                         startActivity(uninstallIntent);*/
                        Log.i("完成", "onStart: 下载完成");
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Message msgFail = new Message();
                        msgFail.what = FAILED;

                        Bundle bundle = new Bundle();

                        bundle.putInt("ErrorCode", error.getExceptionCode());
                        msgFail.setData(bundle);

                        handlerUi.sendMessage(msgFail);
//            if (error.getExceptionCode() == 416) {
//              Intent intent = new Intent(Intent.ACTION_VIEW);
//              intent
//                  .setDataAndType(
//                      FileProvider.getUriForFile(activity, applicationId + ".provider",
//                          new File(filepath.getPath().toString())),
//                      "application/vnd.android.package-archive");
//              activity.startActivity(intent);
//            }
                        Log.i("取消", "onStart: 下载失败" + error.toString());
                    }
                });
    }

    public static void DownLoadHardwareFile(final Context mContext, String downLoadUrl, final String version) {
        //保存位置
        //关于下边的File.separator原文The system-dependent string used to separate components in filenames
        // ('/').
        //其实就是代表了一个斜杠
        final File filepath = new File(FusionCode.DOWNLOAD_SAVE_BIN_PATH + "CardDealer-" + version + ".bin");
        if (!filepath.exists()) {
//            filepath.mkdir();//如果路径不存在就先创建路径
        }
        // 准备进度条Progress弹窗
        final ProgressDialog dialog = new ProgressDialog(mContext);
        dialog.setCancelable(false);// 设置是否可以通过点击Back键取消
        dialog.setTitle("下载中");
        //Progress弹窗设置为水平进度条
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        //httputils网络请求工具
        HttpUtils http = new HttpUtils();

        @SuppressLint("HandlerLeak") final Handler handlerUi = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == START) {
                    dialog.show();//展示关闭弹窗
                } else if (msg.what == COMPLETED) {
                    dialog.dismiss();//关闭弹窗
                    try {
                        Bundle bundle = new Bundle();
                        bundle.putString("fileName", FusionCode.DOWNLOAD_SAVE_BIN_PATH + "CardDealer-" + version + ".bin");

//                        EventBus.getDefault().post(new CardHardwareDownloadEvent(bundle));
                    } catch (Exception e) {
                        e.printStackTrace();
                        dialog.dismiss();
                        Toast.makeText(mContext, "下载出错，请重试！", Toast.LENGTH_LONG).show();
                    }
                } else if (msg.what == FAILED) {
                    Toast.makeText(mContext, "下载失败，请重试！", Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                } else if (msg.what == LOADING) {
                    dialog.setMax((int) msg.getData().getLong("total"));
                    dialog.setProgress((int) msg.getData().getLong("current"));
                }
            }
        };

        //下载请求
        /*
             第一参数：downLoadUrl是网络下载位置
             第二参数：filepath.getPath()是下载保存位置
            第三个参数：如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
            第四个参数：如果从请求返回信息中获取到文件名，下载完成后自动重命名。
            第五个参数：下载的监听
         */

        final HttpHandler handler = http
                .download(downLoadUrl, filepath.getPath(), true, false, new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                        Message msg = new Message();
                        msg.what = START;
                        handlerUi.sendMessage(msg);
                        Log.i("开", "onStart: 开始下载");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        Message msg = new Message();
                        msg.what = LOADING;
                        Bundle bundle = new Bundle();

                        bundle.putLong("total", total);
                        bundle.putLong("current", current);

                        msg.setData(bundle);
                        handlerUi.sendMessage(msg);
                        Log.i("下载中", "onLoading:总共： " + total + "已下" + current);

                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {

                        Message msg = new Message();
                        msg.what = COMPLETED;
                        handlerUi.sendMessage(msg);
                        //卸载
                  /*    Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");//package:com
                  .demo.CanavaCancel应用的包名
                        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
                         startActivity(uninstallIntent);*/
                        Log.i("完成", "onStart: 下载完成");
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Message msgFail = new Message();
                        msgFail.what = FAILED;

                        Bundle bundle = new Bundle();

                        bundle.putInt("ErrorCode", error.getExceptionCode());
                        msgFail.setData(bundle);

                        handlerUi.sendMessage(msgFail);
//            if (error.getExceptionCode() == 416) {
//              Intent intent = new Intent(Intent.ACTION_VIEW);
//              intent
//                  .setDataAndType(
//                      FileProvider.getUriForFile(activity, applicationId + ".provider",
//                          new File(filepath.getPath().toString())),
//                      "application/vnd.android.package-archive");
//              activity.startActivity(intent);
//            }
                        Log.i("取消", "onStart: 下载失败" + error.toString());
                    }
                });
    }

    public static void DownLoadVideoFile(final Context mContext, String downLoadUrl, final String version) {
        //保存位置
        //关于下边的File.separator原文The system-dependent string used to separate components in filenames
        // ('/').
        //其实就是代表了一个斜杠
        final File filepath = new File(FusionCode.DOWNLOAD_SAVE_VIDEO_PATH + "sale_top_cache.mp4");
        if (!filepath.exists()) {
//            filepath.mkdir();//如果路径不存在就先创建路径
        }
        //httputils网络请求工具
        HttpUtils http = new HttpUtils();

        @SuppressLint("HandlerLeak") final Handler handlerUi = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == START) {
                } else if (msg.what == COMPLETED) {
                    try {

                        FileUtil.copyFile(FusionCode.DOWNLOAD_SAVE_VIDEO_PATH + "sale_top_cache.mp4", FusionCode.DOWNLOAD_SAVE_VIDEO_PATH + "sale_top.mp4");
                        FileUtil.deleteFile(FusionCode.DOWNLOAD_SAVE_VIDEO_PATH + "sale_top_cache.mp4");
                        Bundle bundle = new Bundle();
                        bundle.putString("fileName", FusionCode.DOWNLOAD_SAVE_VIDEO_PATH + "sale_top.mp4");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (msg.what == FAILED) {

                } else if (msg.what == LOADING) {

                }
            }
        };

        //下载请求
        /*
             第一参数：downLoadUrl是网络下载位置
             第二参数：filepath.getPath()是下载保存位置
            第三个参数：如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
            第四个参数：如果从请求返回信息中获取到文件名，下载完成后自动重命名。
            第五个参数：下载的监听
         */

        final HttpHandler handler = http
                .download(downLoadUrl, filepath.getPath(), true, false, new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                        Message msg = new Message();
                        msg.what = START;
                        handlerUi.sendMessage(msg);
                        Log.i("开", "onStart: 开始下载");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        Message msg = new Message();
                        msg.what = LOADING;
                        Bundle bundle = new Bundle();

                        bundle.putLong("total", total);
                        bundle.putLong("current", current);

                        msg.setData(bundle);
                        handlerUi.sendMessage(msg);
                        Log.i("下载中", "onLoading:总共： " + total + "已下" + current);

                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {

                        Message msg = new Message();
                        msg.what = COMPLETED;
                        handlerUi.sendMessage(msg);
                        //卸载
                  /*    Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");//package:com
                  .demo.CanavaCancel应用的包名
                        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
                         startActivity(uninstallIntent);*/
                        Log.i("完成", "onStart: 下载完成");
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Message msgFail = new Message();
                        msgFail.what = FAILED;

                        Bundle bundle = new Bundle();

                        bundle.putInt("ErrorCode", error.getExceptionCode());
                        msgFail.setData(bundle);

                        handlerUi.sendMessage(msgFail);
                        Log.i("取消", "onStart: 下载失败" + error.toString());
                    }
                });
    }

}
